/**
 * Channel Object Script Start
 */

(function ( $ ) {
	$.fn.henzChannel = function(options) {
		var defaults = {
			channelId :'henz.report'
		};
		
		var opts = $.extend({}, defaults, options);
		
		console.log('channel....');
		
		var hcOnOpen = function(){
			displayMessage( 'Channel Opened', true );
		};
		
		var hcOnMessage = function( msg ){
			var displayMsg = null;
			//console.log( msg.data );
			var msgObj = JSON.parse( msg.data );
			console.log( msgObj );
			
			if(msgObj.command == 'created'){
				displayMsg = $("<div style='cursor:pointer' onClick='javascript:alert( " + msgObj.reportObj.objKey + " );'>" + msgObj.message + "</div>");
				displayMsg.data( 'msgObj', msgObj.reportObj );
				//msg.data = 
			}else{
				displayMsg = msgObj.message;
			}
			
			displayMessage( displayMsg );
		};
		var hcOnError = function(){
		};
		var hcOnClose = function(){
		};
		
		$.fn.hajax({
			  url : "/channel/token.json"
			, data : {
				channelId : opts.channelId
			}
			, success : function(data, textStatus, jqXHR) {
				opts.token   = data.token;
				opts.channel = new goog.appengine.Channel(opts.token);
				opts.socket  = opts.channel.open();
				
				if(opts.onOpen != null){
					hcOnOpen = opts.onOpen;
				}
				if(opts.onMessage != null){
					hcOnMessage = opts.onMessage;
				}
				if(opts.onError != null){
					hcOnError = opts.onError;
				}
				if(opts.onClose != null){
					hcOnClose = opts.onClose;
				}
				
				opts.socket.onopen    = hcOnOpen;
				opts.socket.onmessage = hcOnMessage;
				opts.socket.onerror   = hcOnError;
				opts.socket.onclose   = hcOnClose;
				
			}
			, error : function(jqXHR, textStatus, errorThrown) {
				console.log(errorThrown);
			}
		});
		
		var displayMessage = function( pMsg, pClearFlag ){
			if(pClearFlag == true){
				$( '.messageDisplay' ).empty();
			}else{
				$( '.messageDisplay' ).append( '<br/>' );
			}
			$( '.messageDisplay' ).append( pMsg );
			$( '.messageDisplay' ).scrollTop( $( '.messageDisplay' ).prop('scrollHeight') );
		};
		
		var sendMessage = function( pMsg ){
			$.fn.hajax({
				  url : "/channel/sendChannel.json"
				, data : { 
					  channelId : opts.channelId
					, message : pMsg 
				}
				, success : function(data, textStatus, jqXHR) {
					console.log( data );
				}
				, error : function(jqXHR, textStatus, errorThrown) {
					console.log(errorThrown);
				}
			});
		}
		
		$( ".msgInput" ).keypress(function( event ) {
			  if ( event.which == 13 ) {
				  var curMsg = $(this).val();
				  if(curMsg != ""){
					  sendMessage( curMsg );
					  $(this).val("");
				  }
			  }
		});
		
		return this.each(function(){$this = $(this);});
		
	};
	
})(jQuery);
